package admin

import (
	"errors"
	"pingbuqingyun_django/app/config/cfg"
	"pingbuqingyun_django/app/models/dao"
	"pingbuqingyun_django/app/models/form"
	"pingbuqingyun_django/app/models/form/memberForm"
	"pingbuqingyun_django/app/models/response/memberResponse"
	"pingbuqingyun_django/pkg/tools"
	"strings"
	"time"
)

type memberService struct {
}

var MemberService = newMemberService()

func newMemberService() *memberService {
	return &memberService{
		//db: tools.DB(),
	}
}

func (a *memberService) InitAdminUser(info cfg.AdminInfo) {
	var user dao.UserModel
	db := tools.DB()
	exist := db.Where(&dao.UserModel{Phone: info.Phone}).First(&user)
	if exist.RowsAffected == 1 {
		return
	}
	createObj := dao.UserModel{
		Phone:     info.Phone,
		UserName:  info.Username,
		Password:  info.Password,
		CreatorId: -1,
		Active:    true,
		IsAdmin:   true,
		IsWechat:  true,
	}
	db.Create(&createObj)
}

// CreateMember
// @Description: 新增会员
// @receiver a
func (a *memberService) CreateMember(forms memberForm.MemberAddForm) (*dao.MemberModel, error) {
	db := tools.DB()
	var (
		member dao.MemberModel
	)
	exist := db.Where("mobile = ?", forms.Mobile).First(&member)
	if exist.RowsAffected == 1 {
		return nil, errors.New("会员信息已经存在，无法创建")
	}

	// Parse the register time string into a time.Time object.
	registerTime, err := time.Parse("2006-01-02", forms.RegisterTime)
	if err != nil {
		return nil, errors.New("无效的注册时间格式，请使用 yyyy-MM-dd格式")
	}

	createObj := dao.MemberModel{
		MemberNo:     forms.MemberNo,
		Mobile:       forms.Mobile,
		Balance:      forms.Balance,
		MemberName:   forms.MemberName,
		Active:       forms.Active, // Convert status to boolean if needed
		RegisterTime: registerTime, // Set the registration time to now
		Store:        forms.Store,
		Remark:       forms.Remark,
	}
	db.Model(&member).Create(&createObj)
	return nil, nil
}

func (a *memberService) UpdateMember(data memberForm.MemberUpdateForm) error {
	db := tools.DB()
	var (
		member dao.MemberModel
	)
	exist := db.Where("id =?", data.Id).First(&member)
	if exist.RowsAffected != 1 {
		return errors.New("会员信息不存在，无法修改")
	}
	// Parse the register time string into a time.Time object.
	registerTime, err := time.Parse("2006-01-02", data.RegisterTime)
	if err != nil {
		return errors.New("无效的注册时间格式，请使用 yyyy-MM-dd 格式")
	}
	member.MemberNo = data.MemberNo
	member.Mobile = data.Mobile
	member.Balance = data.Balance
	member.MemberName = data.MemberName
	member.Active = data.Active        // Convert status to boolean if needed
	member.RegisterTime = registerTime // Set the registration time to now
	member.Store = data.Store
	member.Remark = data.Remark
	db.Save(&member)
	return nil
}

func (a *memberService) SearchMemberList(query memberForm.MemberSearchForm, info form.PaginateForm) interface{} {
	var (
		membersList []dao.MemberModel
		res         memberResponse.MemberListResponses
		count       int64
	)
	db := tools.DB()
	if len(strings.TrimSpace(query.MemberNo)) != 0 {
		db = db.Where("member_no like ?", "%"+query.MemberNo+"%")
	}
	if len(strings.TrimSpace(query.Mobile)) != 0 {
		db = db.Where("mobile like ?", "%"+query.Mobile+"%")
	}
	if len(strings.TrimSpace(query.MemberName)) != 0 {
		db = db.Where("member_name like ?", "%"+query.MemberName+"%")
	}
	if query.Active {
		db = db.Where("active = 0")
	}
	if len(strings.TrimSpace(query.RegisterTime)) != 0 {
		db = db.Where("register_time >= ?", query.RegisterTime)
	}
	if len(strings.TrimSpace(query.Store)) != 0 {
		db = db.Where("store = ?", query.Store)
	}
	db.Model(&dao.MemberModel{}).Count(&count)
	res.Total = count
	db = db.Scopes(PaginateT(int(info.PageNum), int(info.PageSize)))
	db.Order("register_time desc").Find(&membersList)
	for _, i := range membersList {
		var temp memberResponse.MemberResponse
		temp.Id = i.ID
		temp.MemberNo = i.MemberNo
		temp.Mobile = i.Mobile
		temp.Balance = i.Balance
		temp.MemberName = i.MemberName
		temp.Active = i.Active
		temp.Store = i.Store
		temp.Remark = i.Remark
		if !i.RegisterTime.IsZero() {
			temp.RegisterTime = i.RegisterTime.Format("2006-01-02")
		}
		res.List = append(res.List, temp)
	}

	return &res
}

func (a *memberService) DeleteMember(uid, memberId int) error {
	var member dao.MemberModel
	db := tools.DB()
	exist := db.Where("id = ?", memberId).First(&member)
	if exist.RowsAffected != 1 {
		return errors.New("会员信息不存在，无法删除")
	}
	db.Delete(&member)
	return nil
}

func (a *memberService) CountMember() interface{} {
	type CountRes struct {
		Name  string `json:"name"`
		Count int64  `json:"count"`
	}
	var res []CountRes
	var membersList []dao.MemberModel
	db := tools.DB()
	db.Raw("SELECT a.store as name,count(*) as count from pbqy_member a where a.deleted_at is null GROUP BY a.store").Scan(&res)
	exist := db.Find(&membersList)
	res = append(res, CountRes{
		Count: exist.RowsAffected,
		Name:  "全部会员",
	})
	for i := 0; i < len(res)/2; i++ {
		res[i], res[len(res)-1-i] = res[len(res)-1-i], res[i]
	}
	return res
}

// DeactivateMember
//
//	@Description: 禁用会员
//	@receiver u
//	@param uid
//	@param adminId
//	@return error
func (u *memberService) DeactivateMember(uid int, adminId int) error {
	db := tools.DB()
	var data, admin dao.MemberModel
	exist := db.Where("id = ?", uid).First(&data) //被禁用的用户是否存在
	if exist.RowsAffected != 1 {
		return errors.New("用户不存在")
	}
	exist = db.Where("id = ?", adminId).First(&admin) //执行操作的管理员是否存在
	if exist.RowsAffected != 1 {
		return errors.New("执行操作的管理员用户不存在")
	}
	if admin.ID == int64(uid) {
		return errors.New("无法禁用您自己的用户")
	}
	db.Model(&data).Updates(map[string]interface{}{
		"Active":    false,
		"UpdatedAt": time.Now(),
	})
	return nil
}

func (u *memberService) ActivateMember(uid int, adminId int) error {
	db := tools.DB()
	var data, admin dao.MemberModel
	exist := db.Where("id = ?", uid).First(&data)
	if exist.RowsAffected != 1 {
		return errors.New("用户不存在")
	}
	exist = db.Where("id = ?", adminId).First(&admin)
	if exist.RowsAffected != 1 {
		return errors.New("执行操作的管理员用户用户不存在")
	}
	//data.Active = true
	//db.Save(&data)
	db.Model(&data).Updates(map[string]interface{}{
		"Active":    true,
		"UpdatedAt": time.Now(),
	})
	return nil
}

func (u *memberService) RechargeMember(adminId int, forms memberForm.RechargeMemberForm) error {
	db := tools.DB()
	var data, admin dao.MemberModel
	exist := db.Where("id = ?", forms.Id).First(&data)
	if exist.RowsAffected != 1 {
		return errors.New("用户不存在")
	}
	exist = db.Where("id = ?", adminId).First(&admin)
	if exist.RowsAffected != 1 {
		return errors.New("执行操作的管理员用户用户不存在")
	}
	exist = db.Where("mobile = ?", forms.Mobile).First(&data)
	if exist.RowsAffected != 1 {
		return errors.New("用户不存在")
	}
	db.Model(&data).Updates(map[string]interface{}{
		"Balance":   forms.NewBalance,
		"Remark":    forms.Remark,
		"UpdatedAt": time.Now(),
	})
	return nil
}
